﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using bdnt_pets_system.FailureServiceReference;
using System.Collections.ObjectModel;
using bdnt_pets_system_Entity;
using bdnt_pets_system.MyUserControls;
using bdnt_pets_system.DataServiceReference;
using bdnt_pets_system.Tools;

namespace bdnt_pets_system.PageViews.MatePart
{
    public partial class NewMatePartWindow : BaseWindow
    {
        ObservableCollection<Tbl_MatePart> cuPts = new ObservableCollection<Tbl_MatePart>();
        ObservableCollection<Tbl_PartSta_Relation> cuStatParts;
        Tbl_Vehicle CuTbl_Vehicle;
        FailureServiceReference.FailureServiceClient fClient;
        DataServiceReference.DataServiceClient dClient;
        public NewMatePartWindow(ObservableCollection<Tbl_PartSta_Relation> mateParts = null)
        {
            InitializeComponent();
            dClient = new DataServiceClient();
            fClient = new FailureServiceClient();
            cuStatParts = mateParts;
            InitEvent();
        }

        void InitEvent()
        {
            dClient.GetVehicleByProNoOrVinNoCompleted += new EventHandler<DataServiceReference.GetVehicleByProNoOrVinNoCompletedEventArgs>(dClient_GetVehicleByProNoOrVinNoCompleted);
            tbVINNO.KeyDown += new KeyEventHandler(tbVINNO_KeyDown);
            tbBarNo.KeyDown += new KeyEventHandler(tbBarNo_KeyDown);
            fClient.SaveMatePartCompleted += new EventHandler<SaveMatePartCompletedEventArgs>(fClient_SaveMatePartCompleted);
        }

        void fClient_SaveMatePartCompleted(object sender, SaveMatePartCompletedEventArgs e)
        {
            if (e.Result < 1)
                errorMsg.Text = "保存失败";
            else this.DialogResult = true;
        }

        void dClient_GetVehicleByProNoOrVinNoCompleted(object sender, DataServiceReference.GetVehicleByProNoOrVinNoCompletedEventArgs e)
        {
            CuTbl_Vehicle = e.Result;
            if (CuTbl_Vehicle == null)
                errorMsg.Text = "数据库中不存在此车辆信息";
            else tbVINNO.IsEnabled = false;
        }

        void tbVINNO_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (string.IsNullOrEmpty(tbVINNO.Text))
                {
                    errorMsg.Text = "空VINNO";
                    return;
                }
                errorMsg.Text = "";
                dClient.GetVehicleByProNoOrVinNoAsync("", tbVINNO.Text);
            }
        }

        void tbBarNo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                //if (CuTbl_Vehicle == null)
                //{
                //    errorMsg.Text = "请先扫描VINNO";
                //    return;
                //}
                //errorMsg.Text = "";
                if (string.IsNullOrEmpty(tbBarNo.Text))
                {
                    errorMsg.Text = "空条形码";
                    return;
                }
                errorMsg.Text = "";
                AddBarNo();
            }
        }

        void AddBarNo()
        {
            #region
            //if (cuMateParts == null || cuMateParts.Count < 1)
            //{
            //    errorMsg.Text = "当前用户没有任何需要扫描的部件";
            //    //MessageBox.Show("当前用户没有任何需要扫描的部件", "提示", MessageBoxButton.OK);
            //    return;
            //}

            //string cubov = tbBarNo.Text;
            //if (cubov.IndexOf("_") < 0)
            //{
            //    errorMsg.Text = "条形码格式不对";
            //    //MessageBox.Show("条形码格式不对", "提示", MessageBoxButton.OK);
            //    return;
            //}
            //var pLs = cubov.Split('_');
            //var cuPt = cuMateParts.FirstOrDefault(p => p.PartNo == pLs[0]);
            //if (cuPt == null)
            //{
            //    errorMsg.Text = "当前用户没有权限扫描此条形码";
            //    //MessageBox.Show("当前用户没有权限扫描此条形码", "提示", MessageBoxButton.OK);
            //    return;
            //}
            //if (CuTbl_Vehicle.VConfiguration != pLs[1])
            //{
            //    errorMsg.Text = "部件配置与车辆配置不一致";
            //    //MessageBox.Show("当前用户没有权限扫描此条形码", "提示", MessageBoxButton.OK);
            //    return;
            //}
            #endregion

            MyMatePart mmp = new MyMatePart();

            //ContentControl cc = new ContentControl();
            //cc.ContentTemplate = LayoutRoot.Resources["ctBarInfo"] as DataTemplate;
            var cuobj = new Tbl_MatePart() { BARNO = tbBarNo.Text, CREATEUSERID = SessionManager.CurrentUser.Id };
            if (tbBarNo.Text.IndexOf("_") > 0)
            {
                var pLs = tbBarNo.Text.Split('_');
                var cuPt = cuStatParts.FirstOrDefault(p => p.PartNo.ToUpper() == pLs[0].ToUpper());
                if (cuPt != null)
                {
                    cuobj.PARTNO = cuPt.PartNo;
                }
            }
            mmp.BindData(cuobj);
            //cc.DataContext = cuobj;
            cuPts.Add(cuobj);
            spBarNo.Children.Add(mmp);
            tbBarNo.Text = "";
            //mmp.hbSc.Tag = mmp;
            //mmp.hbSc.Click += new RoutedEventHandler(hbSc_Click);
        }

        void hbSc_Click(object sender, RoutedEventArgs e)
        {
            var cuMp = (sender as HyperlinkButton).Tag as MyMatePart;
            cuMp.Visibility = System.Windows.Visibility.Collapsed;
            var cuo = cuMp.Tag as Tbl_MatePart;
            cuPts.Remove(cuo);
        }

        bool ValidateData()
        {
            if (cuStatParts == null || cuStatParts.Count < 1)
            {
                errorMsg.Text = "当前用户没有任何需要扫描的部件";
                //MessageBox.Show("当前用户没有任何需要扫描的部件", "提示", MessageBoxButton.OK);
                return false;
            }

            if (CuTbl_Vehicle == null)
            {
                errorMsg.Text = "请扫描VINNO";
                //MessageBox.Show("当前用户没有任何需要扫描的部件", "提示", MessageBoxButton.OK);
                return false;
            }
            bool re = true;

            var chils = spBarNo.Children.OfType<MyMatePart>().Where(p => p.Visibility == System.Windows.Visibility.Visible);
            foreach (var item in chils)
            {
                var cuV = item.DataContext as Tbl_MatePart;
                //string cubov = cuV.BARNO;
                if (cuV.BARNO.IndexOf("_") <= 0)
                {
                    item.BorderBrush = new SolidColorBrush(Colors.Red);
                    errorMsg.Text = "条形码 " + cuV.BARNO + " 格式不对";
                    //MessageBox.Show("条形码格式不对", "提示", MessageBoxButton.OK);
                    re = false;
                    break;
                }

                var pLs = cuV.BARNO.Split('_');
                var cuPt = cuStatParts.FirstOrDefault(p => p.PartNo == pLs[0]);
                if (cuPt == null)
                {
                    item.BorderBrush = new SolidColorBrush(Colors.Red);
                    errorMsg.Text = "当前用户没有权限扫描条形码 " + cuV.BARNO;
                    //MessageBox.Show("当前用户没有权限扫描此条形码", "提示", MessageBoxButton.OK);
                    re = false;
                    break;
                }

                if (CuTbl_Vehicle.VConfiguration != pLs[1])
                {
                    item.BorderBrush = new SolidColorBrush(Colors.Red);
                    errorMsg.Text = "条形码 " + cuV.BARNO + " 部件配置与车辆配置不一致";
                    //MessageBox.Show("当前用户没有权限扫描此条形码", "提示", MessageBoxButton.OK);
                    re = false;
                    break;
                }
                item.BorderBrush = new SolidColorBrush(Colors.Black);
                cuV.CREATETIME = DateTime.Now;
                cuV.VINNO = CuTbl_Vehicle.VINNo;
            }

            if (re)
            {
                if (cuStatParts.Count > chils.Count())
                {
                    int laC = cuStatParts.Count - chils.Count();
                    if (MessageBox.Show("还有" + laC.ToString() + " 个部件没有扫描，确定要保存吗？", "提示", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                        re = false;
                    else re = true;
                }
            }
            return re;
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            if (!ValidateData())
                return;
            fClient.SaveMatePartAsync(cuPts);
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        //private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        //{
        //    var cuhb = sender as HyperlinkButton;
        //    var cuo = cuhb.Tag as Tbl_MatePart;
        //    cuPts.Remove(cuo);
        //    (cuhb.Parent as StackPanel).Visibility = System.Windows.Visibility.Collapsed;
        //}
    }
}

